-
Notifications
You must be signed in to change notification settings - Fork 0
/
Doubly Linked List - Merge two sorted lists (Iterative).cpp
98 lines (88 loc) · 1.94 KB
/
Doubly Linked List - Merge two sorted lists (Iterative).cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <iostream>
using namespace std;
struct NODE {
int data;
NODE *prev;
NODE *next;
};
class List {
public:
NODE *prevnode = NULL;
NODE *head = NULL;
NODE *tail = NULL;
};
void add(List &obj, int value){
if(obj.head == NULL){
obj.head = new NODE;
obj.head->data = value;
obj.head->next = 0;
obj.tail = obj.head;
} else {
obj.prevnode = obj.tail;
obj.tail->next = new NODE;
obj.tail = obj.tail->next;
obj.tail->prev = obj.prevnode;
obj.tail->data = value;
obj.tail->next = 0;
}
}
List Sorted;
void mergeList(List &listA, List &listB){
NODE *A = listA.head, *B = listB.head;
if(A || B){
NODE *root = new NODE;
NODE *sort = root;
while(!(A == 0 && B == 0)){
if((A && B && A->data <= B->data) || (A && !B)){
sort->next = A;
A = A->next;
} else {
sort->next = B;
B = B->next;
}
Sorted.prevnode = sort;
sort = sort->next;
sort->prev = Sorted.prevnode;
}
Sorted.head = root->next;
Sorted.tail = sort;
Sorted.head->prev = 0;
} else {
cout << "Merge sort not possible" << endl;
}
}
int print(List list){
NODE *ref = list.head;
if(ref == 0){
cout << "[EMPTY LIST]" << endl;
return false;
} else {
while(ref != 0){
cout << ref->data;
ref = ref->next;
if(ref != 0 ) cout << " => ";
}
cout << endl;
return true;
}
}
int main(){
List A, B;
add(A, 10);
add(A, 30);
add(A, 50);
add(A, 70);
add(A, 90);
add(B, 20);
add(B, 40);
add(B, 60);
add(B, 80);
add(B, 100);
cout << "[A] ";
print(A);
cout << "[B] ";
print(B);
mergeList(A, B);
cout << "[S] ";
print(Sorted);
}